package com.zqj.project.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqj.project.common.database.mybatis.conditions.Wraps;
import com.zqj.project.common.exception.BizException;
import com.zqj.project.converter.CartConverter;
import com.zqj.project.entity.CartPO;
import com.zqj.project.entity.PhonePO;
import com.zqj.project.factory.CartFactory;
import com.zqj.project.model.Cart;
import com.zqj.project.repository.CartMapper;
import com.zqj.project.repository.PhoneMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description: CartServiceImpl
 * @Author: 22001010704 Zhang Qijian
 * @CreateTime: 2024/11/8 15:39
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {

    private final CartMapper cartMapper;
    private final PhoneMapper phoneMapper;

    @Override
    public IPage<Cart> page(Cart cart, IPage<Cart> page) {
        final Long count = this.cartMapper.selectCount(CartFactory.lbqWrapper(cart));
        if (Objects.equals(0L, count)) {
            return page;
        }
        page.setTotal(count);
        return page.setRecords(CartConverter.toCartModelList(this.cartMapper.selectPage(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), CartFactory.lbqWrapper(cart)).getRecords()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(Cart cart) {
        CartPO cartPo = this.cartMapper.selectOne(CartFactory.lbqWrapper(cart));
        PhonePO phonePo = this.phoneMapper.selectById(cart.getProductId());
        if (Objects.isNull(phonePo)) {
            throw new BizException("商品不存在");
        }
        cart.setProductName(phonePo.getName());
        if (Objects.nonNull(cartPo)) {
            cartPo.setNumber(cartPo.getNumber() + cart.getNumber());
            return this.cartMapper.updateById(cartPo) == 1;
        }
        return this.cartMapper.insert(CartConverter.toCartPo(cart)) == 1;
    }

    @Override
    public Boolean edit(Cart cart) {
        PhonePO phonePo = this.phoneMapper.selectById(cart.getProductId());
        if (Objects.isNull(phonePo)) {
            throw new BizException("商品不存在");
        }
        cart.setProductName(phonePo.getName());
        return this.cartMapper.updateById(CartConverter.toCartPo(cart)) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Long userId) {
        return this.cartMapper.delete(Wraps.<CartPO>lbU().eq(CartPO::getUserId, userId));
    }

}